//
//  StatusMenuController.swift
//  maste
//
//  Created by 帽子 on 2020/8/9.
//  Copyright © 2020 帽子. All rights reserved.
//  状态栏 controller

import Cocoa

class StatusMenuController: NSObject, NSMenuDelegate {
    // 绑定menu
    @IBOutlet var customMenu: NSMenu!

    let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)

    override func awakeFromNib() {
        statusItem.menu = customMenu
        statusItem.menu!.delegate = self
        if let button = statusItem.button {
            button.target = self
            button.image = NSImage(named: "icon")
//            button.action = #selector(mouseClickHandler(_:))
//            button.sendAction(on: [.leftMouseUp, .rightMouseUp])
        }
    }

    func menuNeedsUpdate(_ menu: NSMenu) {
        let pasteData = UserData.pasteData
        let menuItems = menu.items
        if menuItems.count > 3 {
            var temMenuItems: [NSMenuItem] = []
            // 前边的【全部清除】
            temMenuItems.append(menuItems[0])
            // 后边的【设置】、【退出】
            temMenuItems.append(menuItems[menuItems.count - 2])
            temMenuItems.append(menuItems[menuItems.count - 1])
            menu.removeAllItems()
            for item in temMenuItems {
                menu.addItem(item)
            }
        }
        // 如果复制结果集合，则添加【分割线】
        if pasteData.count > 0 {
            menu.insertItem(.separator(), at: 1)
            menu.insertItem(.separator(), at: 2)
        }
        for (i, item) in pasteData.enumerated() {
            var hotKey = "\(i + 1)"
            if i + 1 > 9 {
                hotKey = ""
            }
            var title = item.content
            if item.content.count > 10 {
                title = title[..<title.index(title.startIndex, offsetBy: 9)] + "..."
            }
            let menuItem = NSMenuItem(title: "\(title)", action: #selector(copyToPasteboard(_:)), keyEquivalent: hotKey)
            menuItem.toolTip = item.content
            // 需要绑定目标 target 是自身，事件才生效
            menuItem.target = self
            menu.insertItem(menuItem, at: i + 2)
        }
    }

    // 处理状态栏菜单的左右键事件
    @objc func mouseClickHandler(_ sender: Any) {
        if let event = NSApp.currentEvent {
            switch event.type {
            case .leftMouseUp:
                // 使用警告窗口示意左键单击
                let alert = NSAlert()
                alert.messageText = "鼠标事件"
                alert.informativeText = "左键单击"
                alert.addButton(withTitle: "关闭")
                alert.window.titlebarAppearsTransparent = true
                alert.runModal()
            default:
                statusItem.menu = customMenu
                statusItem.button?.performClick(nil)
            }
        }
    }

    /*
     * 绑定退出 menuItem 的点击事件
     * 获取剪切板，将选中的菜单子项 menuItem 的内容复制到剪切板中
     */
    @objc func copyToPasteboard(_ sender: Any) {
        let item = sender as! NSMenuItem
        let pboard = NSPasteboard.general
        pboard.declareTypes([.string], owner: nil)
        pboard.setString(item.toolTip!, forType: .string)
        pboard.string(forType: .string)
    }

    // 退出程序
    @IBAction func quitApp(_ sender: Any) {
        NSApplication.shared.terminate(self)
    }

    // 全部清除
    @IBAction func clearCache(_ sender: Any) {
        UserData.pasteData = []
        _ = LocalCacheUtil.save(filename: UserData.historyFileName, value: UserData.pasteData)
    }
}
